package com.qfedu.fmmall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qfedu.fmmall.config.TokenUtils;
import com.qfedu.fmmall.entity.Users;
import com.qfedu.fmmall.mapper.UsersMapper;
import com.qfedu.fmmall.service.UsersService;
import com.qfedu.fmmall.utils.MD5Utils;
import com.qfedu.fmmall.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * <p>
 * 用户  服务实现类
 * </p>
 *
 * @author itcast
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Resource
    private UsersMapper usersMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户登录接口
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public ResultVO login(String username, String password) {
        String md5 = MD5Utils.md5(password);
        Users users = usersMapper.selectOne(new LambdaQueryWrapper<Users>().eq(Users::getUsername, username));
        if (!StringUtils.isEmpty(users)) {
            if (users.getPassword().equals(md5)) {
                String token = TokenUtils.sign(users.getUserId() + "");
                return ResultVO.success(users, token);
            } else {
                return ResultVO.error("密码错误！");
            }
        }
        return ResultVO.error("没有该用户账号！");
    }
    /**
     * 用户注册接口
     * @param username
     * @param password
     * @return
     */
    @Override
    @Transactional
    public ResultVO regist(String username, String password) {
        synchronized (this){
            Users users = usersMapper.selectOne(new LambdaQueryWrapper<Users>().eq(Users::getUsername, username)
                    .eq(Users::getPassword, password));
            if (users == null) {
                users=new Users();
                String md5 = MD5Utils.md5(password);
                users.setPassword(md5);
                users.setUsername(username);
                int i = usersMapper.insert(users);
                if (i > 0) {
                    return ResultVO.success(users,"注册成功！");
                }else {
                    return ResultVO.error("注册运到问题，稍后再试！");
                }
            }
            return ResultVO.error("用户已经被注册");
        }
    }
}
